<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/01/24 12:54:29 $)
// $RCSfile: functions_sla.php,v $ : $Revision: 1.20 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

define("DAY_OPEN", "open");
define("DAY_CLOSE", "close");

/**
* Returns the default overdue hours if available
*/
function returnDefaultOverdueHours()
{
	global $_SWIFT;

	if ($_SWIFT["settings"]["t_encustomoverdue"] == 1)
	{
		$overduehrs = DATENOW+(intval($_SWIFT["settings"]["t_overduehrs"])*60*60);
		$resultVar = array();
		$resultVar["slaplanid"] = $slaplanid;
		$resultVar["duetimeline"] = $overduehrs;
		return $resultVar;
	}

	return false;
}

/**
* Generates a Due Date timeline based on the provided Department, Ticket Status & Priority.
*/
function getDueTimeline($departmentid, $ticketstatusid, $priorityid, $slaplanid = false, $starttimeline = false, $_ignoreslaplanid = false, &$debugdata)
{
	global $dbCore, $_SWIFT;

	if (!$starttimeline)
	{
		$starttimeline = DATENOW;
		$starttimeline += $_SWIFT["timezone"]*60*60;
		$debugdata .= "Starting Timeline is: ".date("d M Y h:i:s A", $starttimeline)."\n";
	}

	if (!_is_array($_SWIFT["slaplancache"]))
	{
		$debugdata .= "No SLA Plan Found!, Returning the default overdue time\n";
		return returnDefaultOverdueHours();
	}

//	echo "Looking for SLA Plan..";
	if ($_ignoreslaplanid == true)
	{
		unset($slaplanid);
	}

	if (!isset($_SWIFT["slaplancache"][$slaplanid]))
	{
		// Our first goal is to find the appropriate SLA Plan for this ticket.
		foreach ($_SWIFT["slaplancache"] as $key=>$val)
		{
			if (!empty($_ignoreslaplanid) && $_ignoreslaplanid == $val["slaplanid"])
			{
//				echo "Ignoring SLA: ".$_ignoreslaplanid."<BR />";
				continue;
			}
//			print_r($val);
//			echo "Department ID: $departmentid<BR />Ticket Status: $ticketstatusid<BR />Priority ID: $priorityid<BR />SLA Plan: $slaplanid";
			if (($val["departmentid"] == $departmentid || $val["departmentid"] == "0") && in_array($ticketstatusid, $val["ticketstatuslink"]) && in_array($priorityid, $val["prioritylink"]))
			{
				// Eureka!
//				echo "Found SLA Plan: ".$val["slaplanid"]."<BR />";
				$debugdata .= "Found SLA Plan: ".$val["slaplanid"]."\n";
				$slaplanid = $val["slaplanid"];
				$_slaplan = $val;
				break;
			}
		}
	} else {
		$debugdata .= "SLA Plan Supplied in Function Args: ".$slaplanid."\n";
		$_slaplan = $_SWIFT["slaplancache"][$slaplanid];
		$slaplanid = $_slaplan["slaplanid"];
	}

//	exit;

	if (!$slaplanid)
	{
		return returnDefaultOverdueHours();
	}

	// By now we should have the appropriate SLA plan for this entry, Get the SLA Schedule associated with this plan
	$_slaschedule = $_SWIFT["slaschedulecache"][$_slaplan["slascheduleid"]];
	$slascheduleid = $_slaplan["slascheduleid"];
	if (!$_slaschedule)
	{
		// WTF? No sla schedule? This is all ScReWeD!
		$debugdata .= "No Schedule Found!";
		return returnDefaultOverdueHours();
	}

	// All going well so far.. now we need to get the due timeline from current time.
	$_slatimeline = date("H:i", $starttimeline); // Generate the 24 hr timeline
	$_currentday = date("w"); // Current day.
	$doloop = true;
	$overdueseconds = $_slaplan["overduehrs"]*60*60;
	$_shiftseconds = $workingseconds = $counter = 0;
	$debugdata .= "SLA Timeline: ".$_slatimeline.", Current Day: ".$_currentday.", Overdue Seconds: ".$overdueseconds."\n";

	$debugdata .= "Starting Loop..\n";
	while ($doloop)
	{
		$counter++;
		if ($counter > 100)
		{
			$debugdata .= "Encountered Fail Safe Counter, Breaking Out..\n";
			break;
		}

		$strday = getStrDayRep($_currentday);
		$debugdata .= "STR Rep for Day: ".$strday."\n";
		$_parsehour = parseSLAHour($_slatimeline);
		$debugdata .= "Parse Hour: ".$_parsehour."\n";
		$shiftcurrentday = false;

		$debugdata .= "Is Day Open? SLA Schedule: ".$slascheduleid.", Current Day: ".$_currentday."\n";
		if (isDayOpen($slascheduleid, $_currentday))
		{
			$debugdata .= $_currentday ." Day is open\n";
			$debugdata .= "Checking Schedule, Parse Hour: ".$_parsehour["hour"].", Parse Min: ".$_parsehour["min"]."\n";
			if (checkTimeSchedule($slascheduleid, $_currentday, $_parsehour["hour"], $_parsehour["min"]))
			{
				// We are currently open!
				$debugdata .= "Schedule is Open\n";
				$closetimeline = dayOpenCloseDiff($slascheduleid, DAY_CLOSE, $_currentday, $_parsehour["hour"], $_parsehour["min"]);
				$workingseconds += $closetimeline;
				$debugdata .= "Close Timeline: ".$closetimeline.", Working Seconds: ".$workingseconds."\n";

				if ($workingseconds > $overdueseconds)
				{
					$workingdiff = $workingseconds-$overdueseconds;
					$_shiftseconds += ($closetimeline-$workingdiff);
					$debugdata .= "Overdue Limit Reached, Shift Seconds: ".$_shiftseconds.", Working Diff: ".$workingdiff.", Overdue Seconds: ".$overdueseconds.", Working Seconds: ".$workingseconds."\n";
					$doloop = false;
				} else {
					$shiftcurrentday = true;
				}
			} else {
				$opentimeline = dayOpenCloseDiff($slascheduleid, DAY_OPEN, $_currentday, $_parsehour["hour"], $_parsehour["min"]);
				$closetimeline = dayOpenCloseDiff($slascheduleid, DAY_CLOSE, $_currentday, $_parsehour["hour"], $_parsehour["min"]);
				$debugdata .= "Not in Schedule, Open: ".$opentimeline.", Close: ".$closetimline."\n";
				if ($opentimeline >= 0)
				{
					$_shiftseconds += $opentimeline;
					$_slatimeline = $_slaschedule[$strday."_open"];
					$debugdata .= "Shifting to next day.\n";
				} else {
					$shiftcurrentday = true;
				}
			}
		} else {
			$shiftcurrentday = true;
		}

		if ($shiftcurrentday)
		{
			$debugdata .= "in Shifting mode\n";
			$_slatimeline = "00:00"; // Reset the timeline..
			$_currentday = getNextDay($_currentday);
			$debugdata .= "Next Day is: ".$_currentday.", ".getStrDayRep($_currentday)."\n";
			$_shiftseconds += getDayTimeLeft($_parsehour["hour"], $_parsehour["min"]);

			$debugdata .= "Time Left in Day: ".$_shiftseconds."\n";
			$daytimeleft = getDayTimeLeft($_parsehour["hour"], $_parsehour["min"]);
			$debugdata .= "Day Time Left: ".$daytimeleft."\n";
		}
	}

	$resultVar = array();
	$resultVar["slaplanid"] = $slaplanid;
	$resultVar["duetimeline"] = DATENOW+$_shiftseconds;
	$resultVar["duediff"] = $_shiftseconds;
	$debugdata .= "Final Shift Seconds: ".$_shiftseconds;
	$debugdata .= "Ticket Due On: ".date("d M Y h:i:s A", $resultVar["duetimeline"])."\n";

	return $resultVar;
}

/**
* Checks to see whether the specified hours and day fall into the OPEN stage for the specified $day
*/
function checkTimeSchedule($slascheduleid, $day, $currenthour, $currentminute)
{
	$opentimeline = dayOpenCloseDiff($slascheduleid, DAY_OPEN, $day, $currenthour, $currentminute);
	$closetimeline = dayOpenCloseDiff($slascheduleid, DAY_CLOSE, $day, $currenthour, $currentminute);

	if ($opentimeline <= 0 && $closetimeline > 0)
	{
		return true;
	}

	return false;
}

/**
* Does a diff on Open or Closed timeline and returns it
*/
function dayOpenCloseDiff($slascheduleid, $daytype, $day, $currenthour, $currentminute)
{
	global $_SWIFT;

	$currenttimeline = mktime($currenthour, $currentminute);

	$dayv = getStrDayRep($day)."_".$daytype;
	if (!empty($_SWIFT["slaschedulecache"][$slascheduleid][$dayv]))
	{
		$_parsehour = parseSLAHour($_SWIFT["slaschedulecache"][$slascheduleid][$dayv]);
	} else {
		return 0;
	}

	$endtimeline = mktime($_parsehour["hour"], $_parsehour["min"]);
	$diff = $endtimeline-$currenttimeline;
	return $diff;
}

/**
* Parse the SLA Hour and return the hours and minutes
*/
function parseSLAHour($slahour)
{
	$slahourarr = explode(":", $slahour);
	return array("hour"=>$slahourarr[0], "min" => $slahourarr[1]);
}

/**
* Gets the amount of time left in current day from the given timeline.
*/
function getDayTimeLeft($currenthour, $currentminute)
{
	$currenttimeline = mktime($currenthour, $currentminute);
	$endtimeline = mktime(23, 59, 59);
	$diff = $endtimeline - $currenttimeline;
	return $diff;
}

/**
* Gets the variable representation for given number
*/
function getStrDayRep($day)
{
	$days = array (0 => "sunday", 1 => "monday", 2 => "tuesday", 3 => "wednesday", 4 => "thursday", 5 => "friday", 6 => "saturday");
	return $days[$day];
}

/**
* Checks to see whether we are open for the current day or not.
*/
function isDayOpen($slascheduleid, $day)
{
	global $_SWIFT;

	$dayv = getStrDayRep($day)."_enabled";
	if ($_SWIFT["slaschedulecache"][$slascheduleid][$dayv] == 1)
	{
		return true;
	} else {
		return false;
	}
}

/**
* Gets the next day from given day ("w")
*/
function getNextDay($day)
{
	if ($day == 6)
	{
		return 0;
	} else {
		return $day+1;
	}
}

/**
* Checks the given hour range. Hours should be in 00:00 (EU) Format.. if the second hr is less than the first one, it errors out
*/
function checkHourRange($firsthr, $secondhr)
{
	// We always expect to have a 24 hr format
	$hrtime1 = explode(":", $firsthr);
	$hrtime2 = explode(":", $secondhr);

	$hrtimeresult1 = mktime($hrtime1[0], $hrtime1[1], 0, date("m"), date("d"), date("Y"));
	$hrtimeresult2 = mktime($hrtime2[0], $hrtime2[1], 0, date("m"), date("d"), date("Y"));

	// secondhr will always have to be greater than the first hour
	if ($hrtimeresult2 <= $hrtimeresult1)
	{
		return "-1";
	} else if ($hrtimeresult2 == $hrtimeresult1) {
		return "0";
	} else {
		$timeresult = $hrtimeresult2-$hrtimeresult1;
		return $timeresult;
	}
}

/**
* Returns the representation of hour according to date setting
*/
function returnParsedHour($houreu)
{
	global $_SWIFT;

	$_hourus = $_houreu = "";

	$_hourarray = explode(":", $houreu);
	
	$_hour = $_hourarray[0];
	$_minute = $_hourarray[1];

	if ($_hour > 12)
	{
		$_ushour = iif(($_hour-12)==0, "12", ($_hour-12));
	} else {
		$_ushour = iif($_hour==0, "12", $_hour);
	}

	$_ampm = iif($_hour>=12, $_SWIFT["language"]["pm"], $_SWIFT["language"]["am"]);

	$euhr = sprintf($_SWIFT["language"]["hourrendereu"], iif($_hour=="0", "00", $_hour), iif($_minute=="0", "00", $_minute));
	$ushr = sprintf($_SWIFT["language"]["hourrenderus"], iif($_ushour=="0", "00", $_ushour), iif($_minute=="0", "00", $_minute), $_ampm);

	return $ushr;
}

/**
* Builds up the select options for all hours.. generated at an interval of 15 minutes
*/
function buildHourSelectOptions($isclosed = false, $fieldname = "")
{
	global $_SWIFT;

	$_options = null;
	$minutes = 0;
	if (!empty($fieldname))
	{
		$nosel = true;
	} else {
		$nosel = false;
	}

	for ($ii=0; $ii<96; $ii++)
	{
		unset($seltext);
		$_hour = floor($minutes/60);
		$_minute = floor($minutes-($_hour*60));
		$_ushour = iif($_hour>=12, iif(($_hour-12)==0, "12", ($_hour-12)), iif($_hour==0, "12", $_hour));
		$_ampm = iif($_hour>=12, $_SWIFT["language"]["pm"], $_SWIFT["language"]["am"]);

		$euhr = sprintf($_SWIFT["language"]["hourrendereu"], iif($_hour=="0", "00", $_hour), iif($_minute=="0", "00", $_minute));
		$ushr = sprintf($_SWIFT["language"]["hourrenderus"], iif($_ushour=="0", "00", $_ushour), iif($_minute=="0", "00", $_minute), $_ampm);
		$storehr = sprintf("%02d", $_hour) .":". sprintf("%02d", $_minute);

		if (($isclosed == false && $ii == 0 && empty($_POST[$fieldname])) || ($isclosed == true && $ii == 95))
		{
			$seltext = iif($nosel==false, " selected");
		}
		
		if ($_POST[$fieldname] == $storehr) {
			$seltext = " selected";
		}		

		$_options .= '<option value="'. $storehr .'"'. $seltext .'>'. htmlspecialchars($ushr) .'</option>'.SWIFT_CRLF;
		$minutes = $minutes+15;
	}

	return $_options;
}

/**
* Inserts a new SLA Plan
*/
function insertSLAPlan($title, $overduehrs, $departmentid, $slascheduleid, $ticketstatusidlist, $priorityidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($ticketstatusidlist) || !_is_array($priorityidlist))
	{
		return false;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."slaplans` (`departmentid`, `slascheduleid`, `title`, `overduehrs`, `dateline`) VALUES ('". intval($departmentid) ."', '". intval($slascheduleid) ."', '". $dbCore->escape($title) ."', '". floatval($overduehrs) ."', '". DATENOW ."');");
	$slaplanid = $dbCore->lastInsertId();

	if (!$slaplanid)
	{
		return false;
	}

	// Now insert the links
	$statuslinksql = $prioritylinksql = array();
	foreach ($ticketstatusidlist as $key=>$val)
	{
		$statuslinksql[] = "('". intval($slaplanid) ."', '". intval($val) ."')";
	}
	$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."slaplanstatuslink` (`slaplanid`, `ticketstatusid`) VALUES ".implode(",", $statuslinksql).";");

	foreach ($priorityidlist as $key=>$val)
	{
		$prioritylinksql[] = "('". intval($slaplanid) ."', '". intval($val) ."')";
	}
	$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."slaplanprioritylink` (`slaplanid`, `priorityid`) VALUES ".implode(",", $prioritylinksql).";");

	// Rebuild the SLA Plan Cache
	rebuildSLAPlanCache();

	return $slaplanid;
}

/**
* Delete the given SLA Plans
*/
function deleteSLAPlans($slaplanidlist)
{
	global $dbCore, $_SWIFT;

	if (!is_array($slaplanidlist) || !count($slaplanidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."slaplans` WHERE `slaplanid` IN (". buildIN($slaplanidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."slaplanstatuslink` WHERE `slaplanid` IN (". buildIN($slaplanidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."slaplanprioritylink` WHERE `slaplanid` IN (". buildIN($slaplanidlist) .");");

	rebuildSLAPlanCache();

	return true;
}

/**
* Clears the SLA Links
*/
function clearSLALinks($slaplanid)
{
	global $dbCore;

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."slaplanstatuslink` WHERE `slaplanid` = '". intval($slaplanid) ."';");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."slaplanprioritylink` WHERE `slaplanid` = '". intval($slaplanid) ."';");

	return true;
}

/**
* Update the SLA Plan
*/
function updateSLAPlan($slaplanid, $title, $overduehrs, $departmentid, $slascheduleid, $ticketstatusidlist, $priorityidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($ticketstatusidlist) || !_is_array($priorityidlist))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."slaplans` SET `departmentid` = '". intval($departmentid) ."', `slascheduleid` = '". intval($slascheduleid) ."', `title` = '". $dbCore->escape($title) ."', `overduehrs` = '". floatval($overduehrs) ."', `dateline` = '". DATENOW ."' WHERE `slaplanid` = '". intval($slaplanid) ."';");

	clearSLALinks($slaplanid);


	// ======= UPDATE LINKS =======
	$statuslinksql = $prioritylinksql = array();
	foreach ($ticketstatusidlist as $key=>$val)
	{
		$statuslinksql[] = "('". intval($slaplanid) ."', '". intval($val) ."')";
	}
	$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."slaplanstatuslink` (`slaplanid`, `ticketstatusid`) VALUES ".implode(",", $statuslinksql).";");

	foreach ($priorityidlist as $key=>$val)
	{
		$prioritylinksql[] = "('". intval($slaplanid) ."', '". intval($val) ."')";
	}
	$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."slaplanprioritylink` (`slaplanid`, `priorityid`) VALUES ".implode(",", $prioritylinksql).";");

	// Rebuild the Cache
	rebuildSLAPlanCache();

	return $slaplanid;
}

/**
* Render the SLA Plan Form for Insert and Edit pages
*/
function renderSLAForm($type)
{
	global $dbCore, $_SWIFT;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["plandetails"]);

	printTextRow("title", $_SWIFT["language"]["plantitle"], $_SWIFT["language"]["desc_plantitle"], "text", $_POST["title"]);
	
	printNumberRow("overduehrs", $_SWIFT["language"]["overduehrs"], $_SWIFT["language"]["desc_overduehrs"], iif(empty($_POST["overduehrs"]), "24", $_POST["overduehrs"]));

	// ======= Render SLA Schedules =======
	$index = 0;
	$dbCore->query("SELECT slascheduleid, title FROM `". TABLE_PREFIX ."slaschedules`;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["slascheduleid"];
		$index++;
	}
	if (!count($options))
	{
		$options[$index]["title"] = $_SWIFT["language"]["noscheduleavailable"];
		$options[$index]["value"] = "";
		$errormessage = iif($errormessage=="", $_SWIFT["language"]["errorinsertschedule"], $errormessage);
	}
	printSelectRow("slascheduleid", $_SWIFT["language"]["planschedule"], $_SWIFT["language"]["desc_planschedule"], $options);

	// ======= Render Ticket Departments =======
	unset($options);
	$options[0]["title"] = $_SWIFT["language"]["alldepartments"];
	$options[0]["value"] = "0";
	$index = 1;
	$dbCore->query("SELECT departmentid, title FROM `". TABLE_PREFIX ."departments` WHERE `departmentmodule` = '". MODULE_TICKETS ."';");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["departmentid"];
		$index++;
	}
	printSelectRow("departmentid", $_SWIFT["language"]["department"], $_SWIFT["language"]["desc_plandepartment"], $options);

	// ======= Render Ticket Status =======
	unset($options);
	$options[0]["title"] = $_SWIFT["language"]["allstatus"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$index = 1;
	$dbCore->query("SELECT ticketstatusid, title FROM `". TABLE_PREFIX ."ticketstatus`;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["ticketstatusid"];
		if (in_array($dbCore->Record["ticketstatusid"], $_POST["ticketstatusid"]))
		{
			$options[$index]["selected"] = true;			
		}
		$index++;
	}
	printSelectMultipleRow("ticketstatusid", $_SWIFT["language"]["planticketstatus"], $_SWIFT["language"]["desc_planticketstatus"], $options);

	// ======= Render Ticket Priorities =======
	unset($options);
	$options[0]["title"] = $_SWIFT["language"]["allpriorities"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$index = 1;
	$dbCore->query("SELECT priorityid, title FROM `". TABLE_PREFIX ."ticketpriorities`;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["priorityid"];
		if (in_array($dbCore->Record["priorityid"], $_POST["priorityid"]))
		{
			$options[$index]["selected"] = true;			
		}
		$index++;
	}
	printSelectMultipleRow("priorityid", $_SWIFT["language"]["planticketpriority"], $_SWIFT["language"]["desc_planticketpriority"], $options);
	

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertplan"], $_SWIFT["language"]["updateplan"]));

	printMainTableFooter();

	addHiddenField("_m", "tickets");
	addHiddenField("_a", iif($type==INSERT, "insertplan", "editplan"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("slaplanid", $_POST["slaplanid"]);
	}
	printFormEnd();
}

/**
* Insert a new SLA Schedule
*/
function insertSLASchedule($title, $_args)
{
	global $dbCore, $_SWIFT;

	if (!is_array($_args) || !count($_args))
	{
		return false;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."slaschedules` (`title`, `sunday_enabled`, `sunday_open`, `sunday_close`, `monday_enabled`, `monday_open`, `monday_close`, `tuesday_enabled`, `tuesday_open`, `tuesday_close`, `wednesday_enabled`, `wednesday_open`, `wednesday_close`, `thursday_enabled`, `thursday_open`, `thursday_close`, `friday_enabled`, `friday_open`, `friday_close`, `saturday_enabled`, `saturday_open`, `saturday_close`, `dateline`) VALUES ('". $dbCore->escape($title) ."', '". intval($_args["sunday_enabled"]) ."', '". $dbCore->escape($_args["sunday_open"]) ."', '". $dbCore->escape($_args["sunday_close"]) ."', '". intval($_args["monday_enabled"]) ."', '". $dbCore->escape($_args["monday_open"]) ."', '". $dbCore->escape($_args["monday_close"]) ."', '". intval($_args["tuesday_enabled"]) ."', '". $dbCore->escape($_args["tuesday_open"]) ."', '". $dbCore->escape($_args["tuesday_close"]) ."', '". intval($_args["wednesday_enabled"]) ."', '". $dbCore->escape($_args["wednesday_open"]) ."', '". $dbCore->escape($_args["wednesday_close"]) ."', '". intval($_args["thursday_enabled"]) ."', '". $dbCore->escape($_args["thursday_open"]) ."', '". $dbCore->escape($_args["thursday_close"]) ."', '". intval($_args["friday_enabled"]) ."', '". $dbCore->escape($_args["friday_open"]) ."', '". $dbCore->escape($_args["friday_close"]) ."', '". intval($_args["saturday_enabled"]) ."', '". $dbCore->escape($_args["saturday_open"]) ."', '". $dbCore->escape($_args["saturday_close"]) ."', '". DATENOW ."');");

	$slascheduleid = $dbCore->lastInsertId();

	rebuildSLAScheduleCache();

	return $slascheduleid;
}

/**
* Delete the given SLA Schedule.. will return false if the SLA Schedule is assigned to a SLA Plan
*/
function deleteSLASchedules($slascheduleidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($slascheduleidlist))
	{
		return false;
	}

	// Check to see if any schedule is assigned to a SLA Plan?
	$_total = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."slaplans` WHERE `slascheduleid` IN (". buildIN($slascheduleidlist) .");");
	if (!empty($_total["totalitems"]))
	{
		// assigned to plan, return false
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."slaschedules` WHERE `slascheduleid` IN (". buildIN($slascheduleidlist) .");");

	rebuildSLAScheduleCache();

	return true;
}

/**
* Update the given SLA Schedule
*/
function updateSLASchedule($slascheduleid, $title, $_args)
{
	global $dbCore, $_SWIFT;

	if (!is_array($_args) || !count($_args))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."slaschedules` SET `title` = '". $dbCore->escape($title) ."', `sunday_enabled` = '". intval($_args["sunday_enabled"]) ."', `sunday_open` = '". $dbCore->escape($_args["sunday_open"]) ."', `sunday_close` = '". $dbCore->escape($_args["sunday_close"]) ."', `monday_enabled` = '". intval($_args["monday_enabled"]) ."', `monday_open` = '". $dbCore->escape($_args["monday_open"]) ."', `monday_close` = '". $dbCore->escape($_args["monday_close"]) ."', `tuesday_enabled` = '". intval($_args["tuesday_enabled"]) ."', `tuesday_open` = '". $dbCore->escape($_args["tuesday_open"]) ."', `tuesday_close` = '". $dbCore->escape($_args["tuesday_close"]) ."', `wednesday_enabled` = '". intval($_args["wednesday_enabled"]) ."', `wednesday_open` = '". $dbCore->escape($_args["wednesday_open"]) ."', `wednesday_close` = '". $dbCore->escape($_args["wednesday_close"]) ."', `thursday_enabled` = '". intval($_args["thursday_enabled"]) ."', `thursday_open` = '". $dbCore->escape($_args["thursday_open"]) ."', `thursday_close` = '". $dbCore->escape($_args["thursday_close"]) ."', `friday_enabled` = '". intval($_args["friday_enabled"]) ."', `friday_open` = '". $dbCore->escape($_args["friday_open"]) ."', `friday_close` = '". $dbCore->escape($_args["friday_close"]) ."', `saturday_enabled` = '". intval($_args["saturday_enabled"]) ."', `saturday_open` = '". $dbCore->escape($_args["saturday_open"]) ."', `saturday_close` = '". $dbCore->escape($_args["saturday_close"]) ."', `dateline` = '". DATENOW ."' WHERE `slascheduleid` = '". intval($slascheduleid) ."';");

	rebuildSLAScheduleCache();

	return true;
}

/**
* Render the SLA Schedule Edit/Insert Form
*/
function renderSLAScheduleForm($type)
{
	global $dbCore, $_SWIFT, $_sladays;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["scheduledetails"]);

	printTextRow("title", $_SWIFT["language"]["scheduletitle"], $_SWIFT["language"]["desc_scheduletitle"], "text", $_POST["title"]);
	
	printDescRow($_SWIFT["language"]["scheduledesc"]);

	if ($type == INSERT)
	{
		$houroption_open = buildHourSelectOptions(false);
		$houroption_close = buildHourSelectOptions(true);
		$enabledcheck = " checked";
		$closedcheck = "";
	}

	foreach ($_sladays as $key=>$val)
	{
		if ($type == EDIT)
		{
			unset($enablecheck);
			unset($closedcheck);

			$houroption_open = buildHourSelectOptions(false, $val."_open");
			$houroption_close = buildHourSelectOptions(true, $val."_close");

			if ($_POST[$val."_enabled"] == "1")
			{
				$enabledcheck = " checked";
			} else {
				$closedcheck = " checked";
			}
		}

		printDefaultDescRow($_SWIFT["language"][$val], '', '<input type="radio" name="'. $val .'_enabled" value="1"'. $enabledcheck .'><select name="'. $val .'_open" class="swiftselect">'. $houroption_open .'</select> =&gt; <select name="'. $val .'_close" class="swiftselect">'. $houroption_close .'</select><br/><input type="radio" name="'. $val .'_enabled" value="0"'. $closedcheck .'/>&nbsp;'.$_SWIFT["language"]["closed"]);
	}


	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertschedule"], $_SWIFT["language"]["updateschedule"]));

	printMainTableFooter();

	addHiddenField("_m", "tickets");
	addHiddenField("_a", iif($type==INSERT, "insertschedule", "editschedule"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("slascheduleid", $_POST["slascheduleid"]);
	}
	printFormEnd();
}

/**
* Rebuild the SLA Plan Cache
*/
function rebuildSLAPlanCache()
{
	global $dbCore, $datastore;

	$slaplancache = $slaplanidlist = array();

	$index = 1;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."slaplans`;");
	while ($dbCore->nextRecord())
	{
		$slaplancache[$dbCore->Record["slaplanid"]] = $dbCore->Record;
		$slaplancache[$dbCore->Record["slaplanid"]]["index"] = $index;
		$slaplancache[$dbCore->Record["slaplanid"]]["ticketstatuslink"] = array();
		$slaplancache[$dbCore->Record["slaplanid"]]["prioritylink"] = array();
		$slaplanidlist[] = $dbCore->Record["slaplanid"];
		$index++;
	}

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."slaplanstatuslink` WHERE `slaplanid` IN (". buildIN($slaplanidlist) .");");
	while ($dbCore->nextRecord())
	{
		$slaplancache[$dbCore->Record["slaplanid"]]["ticketstatuslink"][] = $dbCore->Record["ticketstatusid"];
	}

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."slaplanprioritylink` WHERE `slaplanid` IN (". buildIN($slaplanidlist) .");");
	while ($dbCore->nextRecord())
	{
		$slaplancache[$dbCore->Record["slaplanid"]]["prioritylink"][] = $dbCore->Record["priorityid"];
	}

	$datastore->update("slaplancache", $slaplancache);

	return true;
}

/**
* Rebuild the SLA Schedule Cache
*/
function rebuildSLAScheduleCache()
{
	global $dbCore, $datastore;

	$slaschedulecache = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."slaschedules`;");
	while ($dbCore->nextRecord())
	{
		$slaschedulecache[$dbCore->Record["slascheduleid"]] = $dbCore->Record;
	}

	$datastore->update("slaschedulecache", $slaschedulecache);

	return true;
}
?>